import {defineStore} from "pinia";
import {login, user} from "@api/auth.ts";

export interface IUserState {
    token: string,
    username: string,
    avatar: string,
    permissions: string[],
    info: Object
}

// 用户信息
export const useUserStore = defineStore({
    id: 'app-user',
    state: (): IUserState => ({
        token: localStorage.getItem('token') || '',
        username: '',
        avatar: '',
        permissions: [],
        info: {}
    }),
    getters: {
        getToken(): string {
            return this.token
        },
        getUsername(): string {
            return this.username
        },
        getAvatar(): string {
            return this.avatar
        },
        getPermissions(): string[] {
            return this.permissions
        },
        getInfo(): Object {
            // 判断 this.info 是否为空，如果为空则从服务器获取用户信息
            if (Object.keys(this.info).length === 0) {
                console.log(111)
            } else {
                console.log(11)
            }
            return this.info
        }
    },
    actions: {
        setToken(token: string) {
            this.token = token
            localStorage.setItem('token', token)
        },
        setUsername(username: string) {
            this.username = username
        },
        setAvatar(avatar: string) {
            this.avatar = avatar
        },
        setPermissions(permissions: string[]) {
            this.permissions = permissions
        },
        setUserInfo(info: Object) {
            this.info = info
        },
        // 登录
        async login(userInfo: Object) {
            try {
                const response = await login(userInfo)
                if (response.status === 200) {
                    this.setToken(response.data.access_token);
                    this.getUser()
                }
            } catch (error) {
                console.log(error)
            }
        },
        // 用户个人信息
        async getUser() {
            try {
                const response = await user()
                if (response.status === 200) {
                    this.setUsername(response.data.name)
                    this.setAvatar(response.data.avatar_url)
                    this.setUserInfo(response.data)
                }
            } catch (error) {
                console.log(error)
            }
        },
    }
})